package com.heima.review.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.review.entity.AdComment;
import com.heima.review.entity.AdCommentLike;
import com.heima.review.mapper.AdCommentLikeMapper;
import com.heima.review.service.AdCommentLikeService;
import com.heima.review.service.AdCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-04-10
 */
@Slf4j
@Service
public class AdCommentLikeServiceImpl extends ServiceImpl<AdCommentLikeMapper, AdCommentLike> implements AdCommentLikeService {
    @Autowired
    private AdCommentService commentService;

    /**
     * 文章评论-点赞
     */
    @Override
    public Integer like(CommentLikeDto dto) {
        Integer userId = UserThreadLocalUtils.getUserId();
        AdComment commentDB = commentService.getById(dto.getCommentId()); // 获取当前评论的数据
        // 根据评论ID与userID，查询用户点赞记录表，用于判断当前评论是否已经点赞
        AdCommentLike commentLikeDB = findCommentLikeByUserIdOrCommentId(dto, userId);
        // 当前评论第一次点赞
        if (commentLikeDB == null) {
            // 判断是否是取消点赞，如果是抛出异常
            if (dto.getOperation().equals(CommentLikeDto.operation.CANCEL.getCode())) {
                log.warn("根据评论ID与userID，未从数据库查到该用户的点赞记录，userId：{}, 评论Id：{}", userId, dto.getCommentId());
                throw new LeadException(AppHttpCodeEnum.FAILURE);
            }
            // 将点赞记录写入数据库
            saveCommentLike(dto, userId, commentDB);
            return getLikes(commentDB, 1);
        }
        /* 用户取消点赞 */
        this.removeById(commentLikeDB);
        return getLikes(commentDB, -1);
    }


    /**
     * 根据评论ID与userID，查询用户点赞记录
     *
     * @return 点赞记录
     */
    private AdCommentLike findCommentLikeByUserIdOrCommentId(CommentLikeDto dto, Integer userId) {
        LambdaQueryWrapper<AdCommentLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdCommentLike::getCommentId, dto.getCommentId());
        queryWrapper.eq(AdCommentLike::getUserId, userId);
        return this.getOne(queryWrapper);
    }


    /**
     * 将点赞记录添加数据库
     */
    private void saveCommentLike(CommentLikeDto dto, Integer userId, AdComment commentDB) {
        AdCommentLike addCommentLike = new AdCommentLike();
        addCommentLike.setCommentId(Long.valueOf(dto.getCommentId()));
        addCommentLike.setUserId(userId);
        addCommentLike.setArticleId(commentDB.getArticleId());
        this.save(addCommentLike);
    }


    /**
     * 根据用户操作，将点赞数加一或减一，重新写回数据库
     *
     * @return 操作完成后的点赞数
     */
    private Integer getLikes(AdComment commentDB, Integer like) {
        Integer likes = commentDB.getLikes() + like;
        commentDB.setLikes(likes);
        commentService.updateById(commentDB);
        return likes;
    }
}
